package org.soarsky.wealthchengdu.imageCache;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;

import org.soarsky.wealthchengdu.util.Base64;
import org.soarsky.wealthchengdu.util.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


/**
 * 本地文件处理
 *
 */
public class CacheFileUtil {

	/**
	 * 缓存最大文件数
	 */
	private static final int MAX_FILE_NUM = 50;

	private static final int DEFAULT_CACHE_TIME = 24 * 60 * 60 * 1000; // 1 天清理一次
	/**
	 * 加载缓存文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static Bitmap loadImageFromFile(String rootDir, String fileName) {
		fileName = encodeByse64(fileName);
		Bitmap bitmap = null;		
		if (!Utils.isSDCardEnable()) {
			return null;
		}
		
		try {
			File file = new File(rootDir, fileName);
			if (!file.exists()) {
//				Log.i("ooooo", "get not: "+(rootDir + fileName));
				return null;
			}
//			bitmap = BitmapFactory.decodeFile(fileName);
			bitmap = BitmapFactory.decodeFile(rootDir + fileName);
//			Log.e("ooooo", "read ok: "+(rootDir + fileName));
		} catch (OutOfMemoryError oom) {
			CacheMemUtil.clearCache();				
		} catch (Exception e) {
			Log.e("ooooo", e.toString());
		} 

		return bitmap;
	}
	
	/**
	 * 获取图片保存路径
	 * @param rootDir
	 * @param fileName
	 * @return
	 */
	public static String getImagePathForRoot(String rootDir, String fileName){
		fileName = encodeByse64(fileName);
		File file = new File(rootDir, fileName);
		Log.e("ggggg", "imagePath: "+file.getPath());
		return file.getPath();
	}
	

	/**
	 * 保存缓存文件
	 * 
	 * @param data
	 * @param rootDir
	 * @param fileName
	 * @return
	 */
	public static boolean saveByte2SDCard(byte[] data, String rootDir, String fileName) {
		fileName = encodeByse64(fileName);
		
		/* sdcard可读状态 */
		if (!Utils.isSDCardEnable()) {
			return false;
		}

//		Log.d("ooooo", "save: "+(rootDir + fileName));
		BufferedOutputStream fos = null;
		try {

			File file = new File(rootDir, fileName);
			File parent = file.getParentFile();
			if(!parent.exists()){
				parent.mkdirs();
			}
			file.createNewFile();
			fos = new BufferedOutputStream(new FileOutputStream(file));
			fos.write(data);
//			Log.v("ooooo", "write successful: "+(rootDir + fileName));
			fos.close();
		} catch (Exception e) {
			Log.e("ooooo", e.toString());
			return false;
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
				}
			}
		}

		return true;
	}

	/*
	 * 清理指定文件
	 */
	public static void removeFileByFileName(String rootDir, String fileName) {
		fileName = encodeByse64(fileName);	
		
		if (!Utils.isSDCardEnable()) {
			return;
		}		
		try {
			File file = new File(rootDir + fileName);
			if (file.exists()) {
				file.delete();
			}

		} catch (Exception e) {
		} finally {}

	}
	
	/**
	 * 
	 * 维护缓存文件
	 * <p>
	 * 
	 * @param rootDir
	 *            </p>
	 */
	public static void maintainCacheFile(String rootDir) {
		
		if (!Utils.isSDCardEnable()) {
			return;
		}

		try {
			File file = new File(rootDir);
			if (file.exists() && file.isDirectory()) {
				File[] files = file.listFiles();
				if (files.length > MAX_FILE_NUM) {
					// 大于默认数量清理一半
					Arrays.sort(files, new CompratorByLastModified());
					for (int i = 0, len = files.length - MAX_FILE_NUM / 2; i < len; i++) {
						// long time = files[i].lastModified();
						files[i].delete();
					}
				} else {
					// 小于最大数量清理大于默认日期
					long current = System.currentTimeMillis();
					Arrays.sort(files, new CompratorByLastModified());
					for (int i = 0, len = files.length / 5; i < len; i++) {
						long time = files[i].lastModified();
						if (current - time > DEFAULT_CACHE_TIME) {
							files[i].delete();
						}
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}

	}

	/**
	 * 文件比较
	 * 
	 * @author
	 */
	private static class CompratorByLastModified implements Comparator<File> {
		public int compare(File f1, File f2) {
			long diff = f1.lastModified() - f2.lastModified();
			if (diff > 0)
				return 1;
			else if (diff == 0)
				return 0;
			else
				return -1;
		};

		public boolean equals(Object obj) {
			return true;
		};

	}

	/*
	 * 清理缓存文件
	 */
	public static void clearFiles(String rootDir) {
		if (rootDir == null || rootDir.length() == 0) {
			return;
		}
		
		if (!Utils.isSDCardEnable()) {
			return;
		}

		File file = new File(rootDir);
		if (file.exists() && file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0, len = files.length; i < len; i++) {
				files[i].delete();
			}
		}
	}

	private static final String encodeByse64(String name) {
		try {
//			return Base64.encode(name);
			return Base64.encode(name)+".jpg";
		} catch (Exception e) {
			
		}
		return name;
	}
	
	//获取文件大小
	public static long getFileSizes(File f) throws Exception{//取得文件大小
        long s=0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s= fis.available();
        } else {
            Log.e("ggggg", "文件不存在");
        }
        return s;
    }
    // 递归
	//获取文件夹大小
    public static long getFileSize(File f)throws Exception//取得文件夹大小
    {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++)
        {
            if (flist[i].isDirectory())
            {
                size = size + getFileSize(flist[i]);
            } else
            {
                size = size + flist[i].length();
            }
        }
        return size;
    }
    //因为中英文切换时不好处理，所以采取返回字符串的方式
    public static String FormetFileSize(String filePath) throws Exception{//转换文件大小
    	File file = new File(filePath);
    	long fileSize = CacheFileUtil.getFileSize(file);
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize == 0){
            fileSizeString = 0 + "byte";
            return fileSizeString;
        } else if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "byte";
            return fileSizeString;
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "Kb";
            return fileSizeString;
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "Mb";
            return fileSizeString;
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "Gb";
            return fileSizeString;
        }
//        return fileSizeString;
    }
    
    //返回文件夹中文件数目
    public long getlist(File f){//递归求取目录文件个数
        long size = 0;
        File flist[] = f.listFiles();
        size=flist.length;
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getlist(flist[i]);
                size--;
            }
        }
        return size;

 
   }

}
